package findtheslope85;

import java.io.*;

public class CandidateCode {
	private static int[] minMax(int[] d, int l) {
		int[] m = new int[d.length];
		for(int i = 1; i < l - 1; i++) {
			if(d[i] > d[i - 1] && d[i] > d[i + 1])
				m[i] = 1;
			if(d[i] < d[i - 1] && d[i] < d[i + 1])
				m[i] = -1;
		}
		return m;
	}
	
	private static int slope(int[] m) {
		int c = 0;
		for(int i = 0; i < m.length; i++)
			if(m[i] != 0)
				c++;
		return c;
	}
	
    public static int slope_sum(int n1, int n2) {
    	if(n1 < 101) {
    		if(n2 < 101)
    			return 0;
    		n1 = 101;
    	}
    	// split number n1 to digits
		int l = 0, d[] = new int[10];
		while(n1 > 0) {
			d[l++] = n1 % 10;
			n1 /= 10;
		}
		// split number n2 to digits
		int l2 = 0, d2[] = new int[10];
		while(n2 > 0) {
			d2[l2++] = n2 % 10;
			n2 /= 10;
		}
    	int[] m = minMax(d, l); // minima maxima of current number digits
    	int s = slope(m); // slope of current number
    	int sum = s; // sum of slopes of all the numbers
    	int h = 9; // highest different digit index
    	while(d[h] == d2[h])
    		h--;
    	while(h >= 0) {
	    	int i = 0;
	    	while(i < 10 && d[i] >= 9) {
	    		if(m[i] != 0)
	    			s--;
	    		d[i] = 0;
	    		m[i] = 0;
	    		i++;
	    	}
	    	if(i < 10) {
	    		if(i > 0 && i < l - 1) {
		    		if(m[i] < 0)
		    			s--;
		    		if(m[i] == 0)
		    			s++;
		    		m[i]++;
	    		} else if(i >= l)
	    			l = i + 1;
	    		d[i]++;
	    		if(i + 1 < 10) {
	    			if(m[i + 1] > 0) {
	    				if(d[i + 1] == d[i]) {
	    					s--;
	    					m[i + 1] = 0;
	    				}
	    			}
	    		}
	    		if(i + 2 < 10) {
	    			if(m[i + 1] == 0) {
	    				if(d[i] == d[i + 1] + 1 && d[i + 2] > d[i + 1]) {
	    					s++;
	    					m[i + 1] = -1;
	    				}
	    			}
	    		}
	    		// highest different digit index decreases if the digits at the highest index are equal
	    		if(i == h && d[i] == d2[i])
	    	    	while(h >= 0 && d[h] == d2[h])
	    	    		h--;
	    	}
	    	sum += s;
    	}
    	return sum;
    }
    
	public static void main(String[] args) {
		System.out.println(slope_sum(1, 100));
		System.out.println(slope_sum(100, 150));
		System.out.println(slope_sum(54698, 54800));
	}
}
